// -= code_dragon/detail coding by Scott in 2018-12-13-15:16 with IDE:PyCharm =-
var vm = new Vue({
    el: '#app',
    data: {
        host: host,
        static_host,
        results: {},  // 新闻数据
        token: sessionStorage.token || localStorage.token,
        username: sessionStorage.username || localStorage.username,
        user_id: sessionStorage.user_id || localStorage.user_id,
        avatar: '',
        author: '',
        com_data: [],
        count: 0,
        main_comment: '',
        sub_comment: '',
        // present: '1234567',
    },

    mounted: function () {
        // 判断用户的登录状态
        if (this.user_id && this.token) {
            axios.get(this.host + '/user/', {
                // 向后端传递JWT token的方法
                headers: {
                    'Authorization': 'JWT ' + this.token
                },
                responseType: 'json',
            })
                .then(response => {
                    // 加载用户数据
                    this.user_id = response.data.id;
                    this.username = response.data.username;
                    this.avatar = response.data.avatar;
                    if (!this.avatar) {
                        this.avatar = './img/widget-photo.png'
                    }


                })
                .catch(error => {
                    if (error.response.status == 401 || error.response.status == 403) {
                        var arrUrl = document.location.toString().split('/');
                        localStorage.clear();
                        sessionStorage.clear();
                        location.href = '/index.html?next=/';
                        // location.href = '/person-loginsign.html?next=/' + arrUrl[3];
                    }
                });
        } else {
            this.user_id = null;
            this.username = null;
            this.token = null;
            this.avatar = './img/widget-photo.png'
        }
        // 获取头条详情
        var id = this.get_query_string();
        axios.get(this.host + '/news/' + id, {
            responseType: 'json',
            withCredentials: true,
        }).then(response => {
            this.results = response.data;
            this.author = this.results.author.username;
            document.title = this.results.title
        }).catch(error => {
            console.log(error.response.data);
        });
        // 获取评论
        axios.get(this.host + '/comments/' + id, {
            responseType: 'json',
            withCredentials: true,
        }).then(response => {
            this.com_data = this.serializer(response.data);
            this.count = response.data.length
        }).catch(error => {
            console.log(error.response.data);
        });
    },

    methods: {
        my_switch: function (args) {
            if (this.com_data[args].show_sub) {
                this.com_data[args].show_sub = false;
                this.com_data[args].present = this.com_data[args]['sub'].length.toString() + '条回复';
                return 0
            } else {
                this.com_data[args].show_sub = true;
                this.com_data[args].present = '收起';
                return 0
            }
            // alert(args.currentTarget)
            // $(args.currentTarget).parent().parent().siblings('.inner-list').slideToggle()
        },
        // 提交主评论
        create_comment: function (comment) {
            if (!this.check_user()) {
                if (!this.main_comment) {
                    alert("请输入评论内容!");
                }
                var news_id = this.get_query_string();
                axios.post(this.host + '/comments/', {
                        news: news_id,
                        content: this.main_comment,
                        parent: null,
                    },
                    {
                        headers: {
                            'Authorization': 'JWT ' + this.token
                        },
                        responseType: 'json'
                    }
                ).then(response => {
                    var temp = response.data;
                    temp['sub'] = [];
                    this.com_data.unshift(temp);
                    this.count++;
                    this.main_comment = '';
                    // this.x = 'none';
                    alert("评论成功")
                }).catch(error => {
                    console.log(error.response.data);
                });
            }

        },
        // 少虎的
        on_submit: function (comment) {
            this.check_user();
            if (!this.sub_comment) {
                alert("请输入评论内容!");
                return 0
            }
            var news_id = this.get_query_string();
            axios.post(this.host + '/comments/', {
                    news: news_id,
                    content: this.sub_comment,
                    parent: comment.id,
                }, {
                    headers: {
                        'Authorization': 'JWT ' + this.token
                    },
                    responseType: 'json'
                }
            ).then(response => {
                // this.com_data = this.serializer(response.data);
                comment.sub.unshift(response.data);
                this.count++;
                this.sub_comment = '';
                // this.x = 'none'
                alert("评论成功")
            }).catch(error => {
                console.log('错误');
            });
        },
        // 校验用户是否登录
        check_user: function () {
            if (!this.token) {
                var arrUrl = document.location.toString().split('/');
                location.href = '/person-loginsign.html?next=/' + arrUrl[3]
                return true
            }
        },
        // 获取url路径参数
        get_query_string: function () {
            var url = document.location.toString();
            var arrUrl = url.split('?id=');
            return arrUrl[1]
        },
        serializer: function (args) {
            var dict = {};
            var array = [];
            for (var i = 0, a; a = args[i]; i++) {
                if (!a.parent && !dict.hasOwnProperty(a.id)) {
                    dict[a.id] = [];
                    array.push(a)
                } else if (!a.parent && dict.hasOwnProperty(a.id)) {
                    array.push(a)
                } else if (!dict.hasOwnProperty(a.parent)) {
                    dict[a.parent] = [];
                    dict[a.parent].push(a)
                } else {
                    dict[a.parent].push(a)
                }
            }
            for (var j = 0, b; b = array[j]; j++) {
                b['sub'] = dict[b.id];
                b['show_sub'] = false
                b['present'] = b['sub'].length.toString() + '条回复'
            }
            return array
        },
    }
});